package com.seecen.cywbackend.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecen.cywbackend.utils.JwtHelper;
import com.seecen.cywbackend.utils.Result;
import com.seecen.cywbackend.utils.ResultCodeEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginProtectedIntercepter implements HandlerInterceptor {
    @Resource
    private JwtHelper jwtHelper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行拦截器了！");
        String token=request.getHeader("token");
        boolean expiration=jwtHelper.isExpiration(token);
        if(!expiration){
            return true;
        }
        Result result=Result.build(null, ResultCodeEnum.NOT_LOGIN);
        ObjectMapper objectMapper=new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        response.getWriter().print(json);
        return false;
    }
}
